package traffic_restriction

import (
	"context"
	"errors"
	"zxs-micro-2/zxs-micro-common/zxsContext"
	"zxs-micro-2/zxs-micro-wangguan/options"
)

var trCfg TrafficRestrictionConfig

var (
	TRAFFIC_RESTRICTION_REJECT_ERROR = errors.New("被流量拦截工具给拦截了！")
)

var ipTr = &nameAndOr{
	types: true, key: "remote_ip",
}

func init() {
	options.AddNewCtxOption(TROption)
	trCfg = TrafficRestrictionConfig{
		LimitSet: []LimitConfig{
			{LimitAttrName: ipTr, DurationTime: 1, MaxAccessTime: 100},
		},
	}
}

func TROption(ctx context.Context) (context.Context, error) {
	msg, ok := ctx.Value(zxsContext.CTX_MSG_KEY).(*zxsContext.ZxsContextMsg)
	if !ok {
		//不是zxs-micro的ctx。。。为什么？
		return ctx, zxsContext.UnknownContextError
	}
	values, ok := msg.GetValue(zxsContext.CTX_CONTEXT_OPTION_KEY).(map[string]interface{})
	if !ok {
		//表示optionkey没有正常写入，拦截！
		return ctx, zxsContext.UnknownContextError
	}
	h := GetTRHandler("mem")
	for _, o := range trCfg.LimitSet {
		v := o.LimitAttrName.calValue(values)
		if !h.Do(v, o) {
			return ctx, TRAFFIC_RESTRICTION_REJECT_ERROR
		}
	}
	return ctx, nil
}
